<template>
  <div class="member-management">
    <ReCommonTable
      ref="tableRef"
      title="员工管理"
      :loading="loading"
      :data="tableData"
      :columns="columns"
      :search-fields="searchFields"
      :pagination="pagination"
      @search="handleSearch"
      @refresh="handleRefresh"
      @size-change="handleSizeChange"
      @current-change="handleCurrentPageChange"
      @selection-change="handleSelectionChange"
    >
      <!-- 添加按钮 -->
      <template #toolbar-add>
        <el-button
          type="primary"
          size="small"
          @click="handleAdd"
          :icon="CirclePlus"
          >添加员工</el-button
        >
      </template>
      <template #tstatus="{ row }">
        <el-switch
          v-model="row.t_status"
          active-value="1"
          inactive-value="-1"
          inline-prompt
          active-text="在职"
          inactive-text="离职"
          size="small"
          :loading="row._switchLoading"
          @click="handleSwitchChange(row)"
        />
      </template>
      <!-- 操作列 -->
      <template #action="{ row }">
        <el-button size="small" @click="handleView(row)"> 查看 </el-button>
        <el-button size="small" @click="handleEdit(row)"> 编辑 </el-button>
      </template>
    </ReCommonTable>

    <!-- 会员详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="员工详情"
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="currentEmployee" class="member-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="员工ID">
            {{ currentEmployee.t_id }}
          </el-descriptions-item>
          <el-descriptions-item label="员工类型">
            {{ currentEmployee.t_status == 1 ? "在职" : "离职" }}
          </el-descriptions-item>
          <el-descriptions-item label="员工姓名">
            {{ currentEmployee.t_name || "未填写" }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
            {{ currentEmployee.t_mobile }}
          </el-descriptions-item>
          <el-descriptions-item label="性别">
            {{ currentEmployee.sex }}
          </el-descriptions-item>
          <el-descriptions-item label="员工等级">
            {{ currentEmployee.t_level }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatTimestamp(currentEmployee.t_ctime) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间" :span="2">
            {{ formatTimestamp(currentEmployee.t_utime) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 编辑员工弹窗 -->
    <el-dialog
      v-model="editVisible"
      title="编辑员工"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="90px"
      >
        <el-form-item label="员工姓名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="员工性别" prop="sex">
          <el-select v-model="editForm.sex" placeholder="请选择性别" clearable>
            <el-option label="未知" value="0" />
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="员工等级" prop="level">
          <el-select
            v-model="editForm.level"
            placeholder="请选择员工等级"
            clearable
          >
            <el-option
              v-for="item in levelList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="员工状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio label="1">在职</el-radio>
            <el-radio label="-1">离职</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button
          v-if="isAdding === false"
          type="primary"
          :loading="editLoading"
          @click="handleSaveEdit"
        >
          保存
        </el-button>
        <el-button
          v-if="isAdding === true"
          type="primary"
          :loading="editLoading"
          @click="handleSaveAdd"
        >
          添加
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { ReCommonTable } from "@/components/ReCommonTable";
import type {
  SearchField,
  TableColumn
} from "@/components/ReCommonTable/src/index.vue";
import {
  getEmployeeList,
  switchEmployeeStatus,
  editEmployee,
  addEmployee,
  getEmployeeLevel,
  type AddEmployeeParams,
  type EditEmployeeParams,
  type Employee,
  type EmployeeSearchParams
} from "@/api/employee";
import { el } from "element-plus/es/locale/index.mjs";
import { CirclePlus } from "@element-plus/icons-vue";

defineOptions({
  name: "EmployeeList"
});

// 响应式数据
const loading = ref(false);
const detailVisible = ref(false);
const editVisible = ref(false);
const editLoading = ref(false);
const tableRef = ref();
const editFormRef = ref();
const selectedRows = ref([]);
const levelList = ref([]);
const currentEmployee = ref<Employee | null>(null);

// 搜索表单
const searchForm = ref<EmployeeSearchParams>({});
// 编辑表单
const editForm = ref<EditEmployeeParams>({
  id: "",
  name: "",
  sex: "",
  mobile: "",
  status: "",
  level: ""
});

// 编辑表单验证规则
const editRules = {
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }],
  level: [{ required: true, message: "请输入员工等级", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
  ]
};

// 表格数据
const tableData = ref([]);

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
  disabled: false,
  paginationSize: "default"
});

// 搜索字段配置（根据API文档）
const searchFields: SearchField[] = [
  {
    prop: "keys",
    label: "关键字",
    type: "input",
    placeholder: "请输入员工姓名、手机号或手机号后4位"
  },
  {
    prop: "status",
    label: "状态",
    type: "select",
    options: [
      { label: "在职", value: 1 },
      { label: "离职", value: -1 }
    ],
    placeholder: "请选择状态"
  }
];

// 表格列配置（根据API文档字段）
const columns: TableColumn[] = [
  {
    prop: "t_id",
    label: "员工ID",
    width: 80,
    fixed: "left"
  },
  {
    prop: "t_name",
    label: "员工姓名",
    showOverflowTooltip: true
  },
  {
    prop: "t_mobile",
    label: "员工手机号",
    width: 140
  },
  {
    prop: "t_level",
    label: "员工等级",
    width: 160
  },
  {
    prop: "sex",
    label: "性别",
    width: 80
  },
  {
    prop: "t_status",
    label: "状态",
    width: 160,
    slot: "tstatus"
  },
  {
    prop: "t_ctime",
    label: "创建时间",
    width: 180,
    formatter: row => formatTimestamp(row.t_ctime)
  },
  {
    prop: "t_utime",
    label: "更新时间",
    width: 180,
    formatter: row => formatTimestamp(row.t_utime)
  },
  {
    label: "操作",
    width: 140,
    fixed: "right",
    slot: "action"
  }
];

// 格式化时间戳
const formatTimestamp = (timestamp: string) => {
  if (!timestamp || timestamp === "0") return "";
  const date = new Date(parseInt(timestamp) * 1000);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit"
  });
};

// 事件处理
const handleSearch = (searchParams: any) => {
  console.log("搜索参数:", searchParams);
  searchForm.value = searchParams;
  pagination.current = 1;
  loadData();
};

const handleRefresh = () => {
  loadData();
};

const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1;
  loadData();
};

const handleCurrentPageChange = (current: number) => {
  pagination.current = current;
  loadData();
};

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

const handleView = (row: any) => {
  currentEmployee.value = row;
  detailVisible.value = true;
};
const isAdding = ref(false);
const handleEdit = (row: any) => {
  editForm.value = {
    id: row.t_id,
    name: row.t_name || "",
    sex: row.t_sex || "",
    mobile: row.t_mobile || "",
    level: row.t_level || "",
    status: row.t_status.toString() // 确保状态是字符串
  };
  isAdding.value = false;
  editFormRef.value?.resetFields();
  editVisible.value = true;
};

const handleSaveEdit = async () => {
  if (!editFormRef.value) return;

  try {
    await editFormRef.value.validate();
    editLoading.value = true;

    const response = await editEmployee(editForm.value);

    if (response.code === 1) {
      ElMessage.success(response.msg || "编辑成功");
      editVisible.value = false;
      loadData(); // 重新加载数据
    } else {
      ElMessage.error(response.msg || "编辑失败");
    }
  } catch (error) {
    console.error("编辑会员失败:", error);
    ElMessage.error("编辑失败");
  } finally {
    editLoading.value = false;
  }
};
const handleAdd = () => {
  // 初始化表单数据
  editForm.value = {
    id: "",
    name: "",
    mobile: "",
    sex: "", // 性别可以是 "0"、"1" 或 "2"
    level: "",
    status: "1" // 默认在职
  };
  isAdding.value = true; // 标记为添加操作
  editFormRef.value?.resetFields(); // 重置表单验证状态
  editVisible.value = true; // 显示编辑弹窗（复用编辑弹窗）
};
const handleSaveAdd = async () => {
  if (!editFormRef.value) return;

  try {
    await editFormRef.value.validate();
    editLoading.value = true;

    const params: AddEmployeeParams = {
      name: editForm.value.name,
      mobile: editForm.value.mobile,
      sex: editForm.value.sex,
      level: editForm.value.level,
      status: editForm.value.status
    };

    const response = await addEmployee(params);

    if (response.code === 1) {
      ElMessage.success(response.msg || "添加成功");
      editVisible.value = false;
      loadData(); // 重新加载数据
    } else {
      ElMessage.error(response.msg || "添加失败");
    }
  } catch (error) {
    console.error("添加管理员失败:", error);
    ElMessage.error("添加失败");
  } finally {
    editLoading.value = false;
  }
};
// 加载数据
const loadData = async () => {
  loading.value = true;

  try {
    const params: EmployeeSearchParams = {
      num: pagination.size.toString(),
      page: pagination.current.toString(),
      ...searchForm.value
    };

    // 尝试调用API
    try {
      const response = await getEmployeeList(params);

      if (response.code === 1) {
        tableData.value = response.data.list;
        //pagination.total = response.data.pages * pagination.size;
        pagination.total = response.data.list.length;
        return;
      } else {
        ElMessage.error(response.msg || "数据加载失败");
      }
    } catch (apiError) {
      console.error("API 调用失败:", apiError);
      ElMessage.error("数据加载失败");
    }
  } catch (error) {
    console.error("数据加载错误:", error);
    ElMessage.error("数据加载失败");
  } finally {
    loading.value = false;
  }
};
// 员工状态切换
const handleSwitchChange = async (row: any) => {
  try {
    // 设置 loading 状态
    row._switchLoading = true;
    // 调用更新状态的 API，比如 updateEmployeeStatus
    const response = await switchEmployeeStatus(row.t_id);
    if (response.code == 1) {
      ElMessage.success("状态更新成功");
    } else {
      ElMessage.error("状态更新失败");
      row.t_status = row.t_status === 1 ? -1 : 1; // 回滚状态
    }
  } catch (error) {
    console.error("状态更新出错:", error);
    ElMessage.error("状态更新失败");
    row.t_status = row.t_status === 1 ? -1 : 1; // 回滚状态
  } finally {
    // 清除 loading
    row._switchLoading = false;
  }
  await loadData();
};
//获取员工等级
onMounted(async () => {
  const res = await getEmployeeLevel();
  if (res.code == 1) {
    levelList.value = res.data;
  } else {
    ElMessage.success(res.msg || "数据加载失败");
  }
});
// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.member-management {
  height: 100%;
  background: #f5f7fa;
}

.member-detail {
  max-height: 500px;
  overflow-y: auto;
}

:deep(.el-descriptions) {
  --el-descriptions-item-bordered-label-background: #fafafa;
}

.dark :deep(.el-descriptions) {
  --el-descriptions-item-bordered-label-background: #262727;
}
</style>
